<template>
  <div class="song-management-container">
    <!-- 页面标题 -->
    <div class="page-title">歌曲管理系统</div>

    <!-- 主要内容区 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧歌手筛选区域 -->
      <el-col :span="5">
        <el-card class="filter-card">
          <div slot="header" class="card-header">
            <i class="el-icon-microphone"></i> 歌手筛选
          </div>

          <!-- 歌手搜索框 -->
          <el-input
              v-model="singerFilter"
              clearable
              placeholder="搜索歌手"
              @keyup.enter="searchSingers"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="searchSingers"></el-button>
            </template>
          </el-input>

          <!-- 歌手列表 -->
          <div class="singer-list">
            <div
                :class="{ 'singer-item-active': selectedSingerId === null }"
                class="singer-item"
                @click="handleSingerSelect(null)"
            >
              <i class="el-icon-user-solid"></i>
              <span>全部歌手</span>
            </div>
            <div
                v-for="singer in filteredSingers"
                :key="singer.artistId"
                :class="{ 'singer-item-active': selectedSingerId === singer.artistId }"
                class="singer-item"
                @click="handleSingerSelect(singer)"
            >
              <i class="el-icon-user"></i>
              <span>{{ singer.artistName }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧歌曲管理区域 -->
      <el-col :span="19">
        <!-- 搜索表单 -->
        <el-card class="search-card">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="歌名">
              <el-input v-model="searchForm.songName" clearable placeholder="请输入歌名"/>
            </el-form-item>
            <el-form-item label="专辑">
              <el-input v-model="searchForm.album" clearable placeholder="请输入专辑"/>
            </el-form-item>
            <el-form-item label="曲风">
              <el-select
                  v-model="searchForm.styles"
                  clearable
                  collapse-tags
                  multiple
                  placeholder="请选择曲风"
                  style="width: 200px"
              >
                <el-option
                    v-for="style in styleOptions"
                    :key="style"
                    :label="style"
                    :value="style"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="fetchSongs">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 操作按钮区 -->
        <div class="action-buttons">
          <el-button icon="el-icon-plus" type="primary" @click="openAddSongDialog">
            新增歌曲
          </el-button>
          <el-button
              :disabled="selectedSongIds.length === 0"
              icon="el-icon-delete"
              type="danger"
              @click="batchDeleteSongs"
          >
            批量删除
          </el-button>
          <el-button disabled type="info">
            歌曲总数: {{ total }}
          </el-button>
        </div>

        <!-- 歌曲表格 -->
        <el-card class="table-card">
          <el-table
              v-loading="tableLoading"
              :data="songList"
              border
              element-loading-text="加载中..."
              style="width: 100%"
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"/>
            <el-table-column label="歌曲ID" prop="songId" width="100"/>
            <el-table-column label="封面" prop="coverUrl" width="100">
              <template #default="scope">
                <el-image
                    v-if="scope.row.coverUrl"
                    :preview-src-list="[scope.row.coverUrl]"
                    :src="scope.row.coverUrl"
                    class="song-cover"
                    fit="cover"
                />
                <div v-else class="no-cover">暂无封面</div>
              </template>
            </el-table-column>
            <el-table-column label="歌名" prop="songName"/>
            <el-table-column label="歌手" prop="artistName"/>
            <el-table-column label="专辑" prop="album"/>
            <el-table-column label="曲风" prop="style"/>
            <el-table-column label="时长" prop="duration" width="100">
              <template #default="scope">
                <span>{{ formatDuration(scope.row.duration) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发行日期" prop="releaseTime" width="150"/>
            <el-table-column label="操作" width="350">
              <template #default="scope">
                <el-button icon="el-icon-edit" type="text" @click="openEditSongDialog(scope.row)">
                  编辑
                </el-button>
                <el-button icon="el-icon-delete" type="text" @click="deleteSong(scope.row.songId)">
                  删除
                </el-button>
                <el-dropdown @command="(command) => handleUploadCommand(command, scope.row)">
                  <el-button icon="el-icon-upload" type="text">
                    上传 <i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="cover">
                        <i class="el-icon-picture"></i> 封面
                      </el-dropdown-item>
                      <el-dropdown-item command="audio">
                        <i class="el-icon-music"></i> 音频
                      </el-dropdown-item>
                      <el-dropdown-item command="lyric">
                        <i class="el-icon-document"></i> 歌词
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <!-- 新增：修改时长按钮 -->
                <el-button
                    icon="el-icon-time"
                    type="text"
                    @click="openDurationDialog(scope.row)"
                >
                  时长
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 分页 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentPageChange"
            :current-page="currentPage"
            :page-sizes="[10, 15, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="pagination"
        />
      </el-col>
    </el-row>

    <!-- 新增/编辑歌曲弹窗 -->
    <el-dialog
        v-model="songDialogVisible"
        :close-on-click-modal="false"
        :title="songDialogTitle"
        width="600px"
    >
      <el-form
          ref="songFormRef"
          :model="songForm"
          :rules="songFormRules"
          class="song-form"
          label-width="120px"
      >
        <el-form-item label="歌手" prop="artistId">
          <el-select v-model="songForm.artistId" clearable placeholder="请选择歌手">
            <el-option
                v-for="singer in allSingers"
                :key="singer.artistId"
                :label="singer.artistName"
                :value="singer.artistId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="歌名" prop="name">
          <el-input v-model="songForm.name" placeholder="请输入歌名"/>
        </el-form-item>
        <el-form-item label="专辑" prop="album">
          <el-input v-model="songForm.album" placeholder="请输入专辑"/>
        </el-form-item>
        <el-form-item label="曲风" prop="style">
          <!-- 修改为多选下拉框 -->
          <el-select
              v-model="songForm.style"
              clearable
              collapse-tags
              multiple
              placeholder="请选择曲风"
              style="width: 100%"
          >
            <el-option
                v-for="style in styleOptions"
                :key="style"
                :label="style"
                :value="style"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发行日期" prop="releaseTime">
          <el-date-picker
              v-model="songForm.releaseTime"
              placeholder="选择发行日期"
              style="width: 100%"
              type="date"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <!-- 新增：时长字段 -->
        <el-form-item label="歌曲时长" prop="duration">
          <el-input-number
              v-model="songForm.duration"
              :max="3600"
              :min="1"
              :step="1"
              placeholder="请输入歌曲时长（秒）"
              style="width: 100%"
          />
          <div class="duration-tip">
            当前时长: {{ formatDuration(songForm.duration) }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="songDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSong">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改时长弹窗 -->
    <el-dialog
        v-model="durationDialogVisible"
        :close-on-click-modal="false"
        title="修改歌曲时长"
        width="500px"
    >
      <el-form
          ref="durationFormRef"
          :model="durationForm"
          :rules="durationFormRules"
          label-width="120px"
      >
        <el-form-item label="当前歌曲">
          <div class="current-song-info">
            <strong>{{ currentSongInfo.songName }}</strong>
            <div class="song-details">
              {{ currentSongInfo.artistName }} - {{ currentSongInfo.album }}
            </div>
            <div class="current-duration">
              当前时长: {{ formatDuration(currentSongInfo.duration) }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="新时长" prop="duration">
          <div class="duration-input-group">
            <el-input-number
                v-model="durationForm.duration"
                :max="3600"
                :min="1"
                :step="1"
                placeholder="请输入时长（秒）"
                style="width: 200px"
            />
            <span class="duration-preview">
              预览: {{ formatDuration(durationForm.duration) }}
            </span>
          </div>
          <div class="duration-tips">
            <p>💡 提示：</p>
            <ul>
              <li>时长单位为秒</li>
              <li>常见歌曲时长：3分钟=180秒，4分钟=240秒，5分钟=300秒</li>
              <li>范围：1秒 - 60分钟（3600秒）</li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="durationDialogVisible = false">取消</el-button>
        <el-button :loading="durationLoading" type="primary" @click="saveDuration">确定</el-button>
      </template>
    </el-dialog>

    <!-- 上传封面弹窗 -->
    <el-dialog
        v-model="coverUploadVisible"
        :close-on-click-modal="false"
        title="上传歌曲封面"
        width="400px"
    >
      <div class="upload-component">
        <el-upload
            ref="coverUploadRef"
            :before-upload="beforeCoverUpload"
            :file-list="coverFileList"
            :http-request="handleCoverUpload"
            accept="image/*"
            class="upload-demo"
        >
          <template #trigger>
            <el-button size="small" type="primary">选择图片</el-button>
          </template>
          <div class="el-upload__tip">
            只能上传jpg/png文件，且不超过2MB
          </div>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="coverUploadVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 上传音频弹窗 -->
    <el-dialog
        v-model="audioUploadVisible"
        :close-on-click-modal="false"
        title="上传歌曲音频"
        width="500px"
    >
      <div class="upload-component">
        <el-upload
            ref="audioUploadRef"
            :before-upload="beforeAudioUpload"
            :file-list="audioFileList"
            :http-request="handleAudioUpload"
            :on-error="handleAudioError"
            :on-success="handleAudioSuccess"
            accept=".mp3,.wav,.ogg,.m4a"
            class="upload-demo"
            drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将音频文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 mp3/wav/ogg/m4a 文件，且不超过 50MB
            </div>
          </template>
        </el-upload>

        <!-- 上传进度显示 -->
        <div v-if="uploadProgress > 0" class="upload-progress">
          <el-progress :percentage="uploadProgress" :stroke-width="8" :text-inside="true"/>
          <div class="progress-text">上传中... {{ uploadProgress }}%</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="audioUploadVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 上传歌词弹窗 -->
    <el-dialog
        v-model="lyricUploadVisible"
        :close-on-click-modal="false"
        title="上传歌曲歌词"
        width="400px"
    >
      <div class="upload-component">
        <el-upload
            ref="lyricUploadRef"
            :before-upload="beforeLyricUpload"
            :file-list="lyricFileList"
            :http-request="handleLyricUpload"
            accept=".lrc,.txt"
            class="upload-demo"
        >
          <template #trigger>
            <el-button size="small" type="primary">选择歌词文件</el-button>
          </template>
          <div class="el-upload__tip">
            只能上传lrc或txt文件，且不超过1MB
          </div>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="lyricUploadVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import http from '@/request/http.js' // 导入封装好的http

// 曲风选项列表 - 更新为您指定的选项
const styleOptions = ref([
  '欧美流行', '电子', '华语流行', '非洲节拍', '粤语流行',
  '原声带', '嘻哈说唱', '摇滚', '节奏布鲁斯', '韩国流行',
  '轻音乐', '乡村', '古典', '国风', '日本流行'
])

// 歌手筛选相关
const singerFilter = ref('')
const allSingers = ref([])
const selectedSingerId = ref(null)

// 过滤后的歌手列表
const filteredSingers = computed(() => {
  if (!singerFilter.value.trim()) {
    return allSingers.value
  }
  return allSingers.value.filter(singer =>
      singer.artistName.toLowerCase().includes(singerFilter.value.toLowerCase())
  )
})

// 歌曲查询相关
const searchForm = reactive({
  songName: '',
  album: '',
  styles: []
})
const songList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedSongIds = ref([])
const tableLoading = ref(false)

// 弹窗相关 - 歌曲
const songDialogVisible = ref(false)
const songDialogTitle = ref('新增歌曲')
const songFormRef = ref(null)
const songForm = reactive({
  id: null,
  artistId: '',
  name: '',
  album: '',
  style: [], // 改为数组类型，支持多选
  releaseTime: '',
  duration: 0 // 新增：时长字段
})
const songFormRules = {
  artistId: [{required: true, message: '请选择歌手', trigger: 'change'}],
  name: [{required: true, message: '请输入歌名', trigger: 'blur'}],
  album: [{required: true, message: '请输入专辑', trigger: 'blur'}],
  style: [
    {required: true, message: '请选择曲风', trigger: 'change'},
    {type: 'array', min: 1, message: '至少选择一个曲风', trigger: 'change'}
  ],
  releaseTime: [{required: true, message: '请选择发行日期', trigger: 'change'}],
  duration: [
    {required: true, message: '请输入歌曲时长', trigger: 'blur'},
    {type: 'number', min: 1, message: '时长必须大于0秒', trigger: 'blur'}
  ]
}

// 时长修改相关
const durationDialogVisible = ref(false)
const durationFormRef = ref(null)
const durationLoading = ref(false)
const currentSongInfo = ref({
  songId: null,
  songName: '',
  artistName: '',
  album: '',
  duration: 0
})
const durationForm = reactive({
  duration: 0
})
const durationFormRules = {
  duration: [
    {required: true, message: '请输入歌曲时长', trigger: 'blur'},
    {type: 'number', min: 1, message: '时长必须大于0秒', trigger: 'blur'},
    {type: 'number', max: 3600, message: '时长不能超过3600秒', trigger: 'blur'}
  ]
}

// 上传相关
const coverUploadVisible = ref(false)
const audioUploadVisible = ref(false)
const lyricUploadVisible = ref(false)
const currentSongId = ref(null)
const coverFileList = ref([])
const audioFileList = ref([])
const lyricFileList = ref([])
const uploadProgress = ref(0) // 上传进度

// 上传组件引用
const coverUploadRef = ref(null)
const audioUploadRef = ref(null)
const lyricUploadRef = ref(null)

// 格式化时长显示（秒转换为分:秒）
const formatDuration = (seconds) => {
  if (!seconds || isNaN(seconds)) return '0:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 获取所有歌手
const fetchAllSingers = async () => {
  try {
    const res = await http.get('/admin/getAllArtistNames')
    if (res.code === 0 && res.data) {
      allSingers.value = res.data
    } else {
      ElMessage.warning(res.message || '获取歌手列表失败')
    }
  } catch (error) {
    console.error('获取歌手列表失败:', error)
    ElMessage.error('获取歌手列表失败')
  }
}

// 搜索歌手
const searchSingers = () => {
  // 搜索逻辑已经在computed属性filteredSingers中实现
  // 这里只需要触发重新计算
}

// 选择歌手
const handleSingerSelect = (singer) => {
  if (!singer) {
    // 选择全部歌手
    selectedSingerId.value = null
  } else {
    selectedSingerId.value = singer.artistId
  }
  // 重置页码，重新加载数据
  currentPage.value = 1
  fetchSongs()
}

// 获取歌曲列表 - 统一使用 /admin/getAllSongsByArtist 接口
const fetchSongs = async () => {
  tableLoading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      songName: searchForm.songName || '',
      album: searchForm.album || ''
    }

    // 如果选择了歌手，添加artistId参数
    if (selectedSingerId.value) {
      params.artistId = selectedSingerId.value
    }

    // 处理曲风搜索条件 - 将数组转换为逗号分隔的字符串
    if (searchForm.styles && searchForm.styles.length > 0) {
      params.style = searchForm.styles.join(',')
    }

    console.log('调用歌曲接口，参数:', params)

    const res = await http.post('/admin/getAllSongsByArtist', params)

    if (res.code === 0 && res.data) {
      // 处理返回的数据结构
      songList.value = res.data.items || res.data.records || []
      total.value = res.data.total || 0
      console.log('歌曲接口返回:', res.data)
    } else {
      songList.value = []
      total.value = 0
      if (res.message && res.message !== '获取歌曲列表失败') {
        ElMessage.warning(res.message)
      }
    }
  } catch (error) {
    console.error('获取歌曲列表失败:', error)
    ElMessage.error('获取歌曲列表失败')
    songList.value = []
    total.value = 0
  } finally {
    tableLoading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.songName = ''
  searchForm.album = ''
  searchForm.styles = []
  currentPage.value = 1
  fetchSongs()
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置页码
  fetchSongs()
}

const handleCurrentPageChange = (val) => {
  currentPage.value = val
  fetchSongs()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedSongIds.value = selection.map(item => item.songId)
}

// 打开新增歌曲弹窗
const openAddSongDialog = () => {
  songDialogTitle.value = '新增歌曲'
  Object.assign(songForm, {
    id: null,
    artistId: selectedSingerId.value || '', // 默认选中当前筛选的歌手
    name: '',
    album: '',
    style: [], // 初始化为空数组
    releaseTime: '',
    duration: 180 // 默认3分钟
  })
  songDialogVisible.value = true
}

// 打开编辑歌曲弹窗
const openEditSongDialog = (row) => {
  songDialogTitle.value = '编辑歌曲'

  // 处理曲风数据：将字符串转换为数组
  let styleArray = []
  if (row.style) {
    if (typeof row.style === 'string') {
      // 如果是逗号分隔的字符串，分割成数组
      styleArray = row.style.split(',').map(s => s.trim()).filter(s => s)
    } else if (Array.isArray(row.style)) {
      // 如果已经是数组，直接使用
      styleArray = row.style
    }
  }

  Object.assign(songForm, {
    id: row.songId,
    artistId: row.artistId,
    name: row.songName,
    album: row.album,
    style: styleArray, // 使用处理后的数组
    releaseTime: row.releaseTime,
    duration: row.duration || 0 // 新增：设置时长
  })
  songDialogVisible.value = true
}

// 打开修改时长弹窗
const openDurationDialog = (row) => {
  // 设置当前歌曲信息
  currentSongInfo.value = {
    songId: row.songId,
    songName: row.songName,
    artistName: row.artistName,
    album: row.album,
    duration: row.duration || 0
  }

  // 设置表单数据
  durationForm.duration = row.duration || 0

  // 打开弹窗
  durationDialogVisible.value = true
}

// 保存歌曲时长
const saveDuration = async () => {
  if (!durationFormRef.value) return

  try {
    // 表单验证
    await durationFormRef.value.validate()

    durationLoading.value = true

    const res = await http.patch(`/admin/updateSongDuration/${currentSongInfo.value.songId}`, {
      duration: durationForm.duration
    })

    if (res.code === 0) {
      ElMessage.success('歌曲时长修改成功')
      durationDialogVisible.value = false
      fetchSongs() // 刷新列表
    } else {
      ElMessage.error(res.message || '歌曲时长修改失败')
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      // 表单验证失败，不做额外处理
      return
    }
    console.error('修改歌曲时长失败:', error)
    ElMessage.error('歌曲时长修改失败')
  } finally {
    durationLoading.value = false
  }
}

// 保存歌曲
const saveSong = async () => {
  if (!songFormRef.value) return

  try {
    // 表单验证
    await songFormRef.value.validate()

    // 处理曲风数据：将数组转换为逗号分隔的字符串
    const submitData = {
      ...songForm,
      style: songForm.style.join(',') // 将数组转换为字符串
    }

    if (songForm.id) {
      // 编辑歌曲
      const res = await http.put('/admin/updateSong', {
        id: submitData.id,
        artistId: submitData.artistId,
        name: submitData.name,
        album: submitData.album,
        style: submitData.style,
        releaseTime: submitData.releaseTime,
        duration: submitData.duration // 新增：提交时长
      })

      if (res.code === 0) {
        ElMessage.success('歌曲更新成功')
        songDialogVisible.value = false
        fetchSongs()
      } else {
        ElMessage.error(res.message || '歌曲更新失败')
      }
    } else {
      // 新增歌曲
      const res = await http.post('/admin/addSong', {
        artistId: submitData.artistId,
        name: submitData.name,
        album: submitData.album,
        style: submitData.style,
        releaseTime: submitData.releaseTime,
        duration: submitData.duration // 新增：提交时长
      })

      if (res.code === 0) {
        ElMessage.success('歌曲新增成功')
        songDialogVisible.value = false
        fetchSongs()
      } else {
        ElMessage.error(res.message || '歌曲新增失败')
      }
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      // 表单验证失败，不做额外处理
      return
    }
    console.error('保存歌曲失败:', error)
    ElMessage.error(songForm.id ? '歌曲更新失败' : '歌曲新增失败')
  }
}

// 删除歌曲
const deleteSong = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这首歌曲吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const res = await http.delete(`/admin/deleteSong/${id}`)
    if (res.code === 0) {
      ElMessage.success('歌曲删除成功')
      fetchSongs()
    } else {
      ElMessage.error(res.message || '歌曲删除失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('歌曲删除失败')
    console.error(error)
  }
}

// 批量删除歌曲
const batchDeleteSongs = async () => {
  if (selectedSongIds.value.length === 0) return

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的${selectedSongIds.value.length}首歌曲吗？`,
        '批量删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const res = await http.delete('/admin/deleteSongs', {
      data: selectedSongIds.value
    })

    if (res.code === 0) {
      ElMessage.success('批量删除成功')
      fetchSongs()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('批量删除失败')
    console.error(error)
  }
}

// 处理上传命令
const handleUploadCommand = (command, row) => {
  console.log('上传命令:', command, '歌曲:', row)
  currentSongId.value = row.songId
  switch (command) {
    case 'cover':
      coverFileList.value = []
      coverUploadVisible.value = true
      break
    case 'audio':
      audioFileList.value = []
      uploadProgress.value = 0 // 重置进度
      audioUploadVisible.value = true
      break
    case 'lyric':
      lyricFileList.value = []
      lyricUploadVisible.value = true
      break
  }
}

// 自定义封面上传处理
const handleCoverUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('cover', options.file)

    const res = await http.patch(`/admin/updateSongCover/${currentSongId.value}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (res.code === 0) {
      ElMessage.success('封面上传成功')
      coverUploadVisible.value = false
      fetchSongs()
    } else {
      ElMessage.error(res.message || '封面上传失败')
    }
  } catch (error) {
    console.error('封面上传失败:', error)
    ElMessage.error('封面上传失败: ' + (error.response?.data?.message || error.message))
  }
}

// 自定义音频上传处理 - 修复版本
const handleAudioUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('audio', options.file)

    console.log('开始上传音频，歌曲ID:', currentSongId.value, '文件:', options.file.name)

    // 使用正确的URL路径 - 根据您的后端接口
    const res = await http.patch(`/admin/updateSongAudio/${currentSongId.value}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          uploadProgress.value = progress
          console.log('上传进度:', progress + '%')
        }
      }
    })

    if (res.code === 0) {
      ElMessage.success('音频上传成功')
      audioUploadVisible.value = false
      uploadProgress.value = 0
      fetchSongs()
    } else {
      ElMessage.error(res.message || '音频上传失败')
      uploadProgress.value = 0
    }
  } catch (error) {
    console.error('音频上传失败:', error)
    ElMessage.error('音频上传失败: ' + (error.response?.data?.message || error.message))
    uploadProgress.value = 0
  }
}

// 音频上传成功处理
const handleAudioSuccess = (response, file, fileList) => {
  console.log('音频上传成功:', response)
  if (response.code === 0) {
    ElMessage.success('音频上传成功')
    audioUploadVisible.value = false
    fetchSongs()
  }
}

// 音频上传失败处理
const handleAudioError = (error, file, fileList) => {
  console.error('音频上传失败:', error)
  ElMessage.error('音频上传失败')
}

// 自定义歌词上传处理
const handleLyricUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('lyric', options.file)

    const res = await http.patch(`/admin/updateSongLyric/${currentSongId.value}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (res.code === 0) {
      ElMessage.success('歌词上传成功')
      lyricUploadVisible.value = false
      fetchSongs()
    } else {
      ElMessage.error(res.message || '歌词上传失败')
    }
  } catch (error) {
    console.error('歌词上传失败:', error)
    ElMessage.error('歌词上传失败: ' + (error.response?.data?.message || error.message))
  }
}

// 封面上传前验证
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  return true
}

// 音频上传前验证 - 放宽限制
const beforeAudioUpload = (file) => {
  const isAudio = file.type.startsWith('audio/') ||
      ['.mp3', '.wav', '.ogg', '.m4a'].some(ext => file.name.toLowerCase().endsWith(ext))
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAudio) {
    ElMessage.error('只能上传音频文件 (mp3, wav, ogg, m4a)!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('音频大小不能超过 50MB!')
    return false
  }

  console.log('音频文件验证通过:', file.name, '大小:', (file.size / 1024 / 1024).toFixed(2) + 'MB')
  return true
}

// 歌词上传前验证
const beforeLyricUpload = (file) => {
  const isLrcOrTxt = file.name.endsWith('.lrc') || file.name.endsWith('.txt')
  const isLt1M = file.size / 1024 / 1024 < 1

  if (!isLrcOrTxt) {
    ElMessage.error('只能上传lrc或txt文件!')
    return false
  }
  if (!isLt1M) {
    ElMessage.error('歌词文件大小不能超过 1MB!')
    return false
  }

  return true
}

// 初始化
onMounted(() => {
  fetchAllSingers()
  fetchSongs()
})
</script>

<style scoped>
.song-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #1f2329;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 24px;
  background-color: #409eff;
  margin-right: 10px;
  border-radius: 2px;
}

.main-content {
  margin-bottom: 20px;
}

.filter-card {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.card-header i {
  margin-right: 8px;
}

.singer-list {
  margin-top: 15px;
  flex: 1;
  overflow-y: auto;
  max-height: 600px; /* 设置最大高度，确保滚动条出现 */
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 5px;
}

.singer-item {
  padding: 10px 15px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.singer-item:hover {
  background-color: #f5f7fa;
}

.singer-item-active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: bold;
}

.singer-item i {
  margin-right: 8px;
  width: 16px;
  text-align: center;
}

.search-card {
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-buttons {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-card {
  margin-bottom: 15px;
}

.song-cover {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.no-cover {
  width: 60px;
  height: 60px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.pagination {
  text-align: right;
  margin-top: 15px;
}

.upload-component {
  margin-top: 15px;
}

.upload-progress {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.progress-text {
  text-align: center;
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

/* 新增时长相关样式 */
.duration-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.current-song-info {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.current-song-info .song-details {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.current-song-info .current-duration {
  color: #e6a23c;
  font-weight: bold;
}

.duration-input-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.duration-preview {
  color: #409eff;
  font-weight: bold;
}

.duration-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.duration-tips p {
  margin: 0 0 5px 0;
  font-weight: bold;
}

.duration-tips ul {
  margin: 0;
  padding-left: 15px;
}

.duration-tips li {
  margin-bottom: 2px;
}

/* 滚动条样式优化 */
.singer-list::-webkit-scrollbar {
  width: 6px;
}

.singer-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.singer-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.singer-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 上传组件样式优化 */
:deep(.upload-demo) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100% !important;
}
</style>